package com.zy.config;

import com.zy.pojo.Role;
import com.zy.service.JurisdictionService;
import com.zy.service.RoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

public class HomeRealm extends AuthorizingRealm {
    private RoleService roleService;
    private JurisdictionService jurisdictionService;

    public JurisdictionService getJurisdictionService() {
        return jurisdictionService;
    }

    public void setJurisdictionService(JurisdictionService jurisdictionService) {
        this.jurisdictionService = jurisdictionService;
    }

    public RoleService getRoleService() {
        return roleService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Role role = (Role) principalCollection.getPrimaryPrincipal();
        List<String > percodes= jurisdictionService.getPercodes(role.getCid());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(percodes);
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Role role = roleService.getRoleUsername(username);
        if (role == null){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(role,role.getPassword(),ByteSource.Util.bytes(role.getSalt()),getName());
        return simpleAuthenticationInfo;
    }
}
